<style scoped>
.clientReturn {
  margin-right: 0.5vw;
  padding: 0 15px;
  background-color: white;
  height: 95vh;
  position: relative;
  overflow-y: hidden;
}
.clientReturn_top {
  display: flex;
  padding: 1.5vh 0;
  white-space: nowrap;
}
.t_content {
  margin: 0 8px 0 12px;
  padding-top: 3px;
  display: inline-block;
}
.t_content1 {
  padding-top: 3px;
  margin: 0 6px 0 0;
}
.clientReturn input:focus {
  outline: none;
  border: 1px solid #017aff;
}
.inp {
  border: 1px solid #dbdbdb;
  border-radius: 3px;
  height: 30px;
  padding: 0 15px;
}
.inp2 {
  width: 8vw;
}
.inp3 {
  width: 3vw;
  margin-right: 0.5vw;
  padding: 0 5px;
}
.inp4 {
  width: 4.5vw;
}
.inp5 {
  width: 150px;
  margin: 0 0 0 16px;
}
.a_color {
  color: #017aff;
}
.clientReturn_c {
  display: flex;
  width: 100%;
  height: 88%;
  border-top: 2px solid #f4f4f4;
}
/*                   566464646*/
.content1 {
  width: 35%;
  border-right: 2px solid #f4f4f4;
  padding-right: 10px;
  height: 87vh;
}
.content2 {
  width: 65%;
  /* height: 100%; */
  padding-left: 10px;
}
.content1_1 {
  display: flex;
  margin: 1.5vh 0;
  overflow: hidden;
}
.c_button {
  width: 35px;
  height: 30px;
  margin: 0 0 0 -1px;
  /* padding:4px 6px 0 0; */
  background: #dbdbdb;
  font-size: 13px;
  border: 0px solid #dbdbdb;
  outline: none;
}
.hand {
  cursor: pointer;
}
.c2 {
  display: flex;
  margin: 1.5vh 0;
  flex-wrap: nowrap;
  justify-content: space-between;
}
.c2_2 {
  display: flex;
}
.c2_1 {
  display: flex;
}
.c2_2 p {
  display: inline-block;
  line-height: 30px;
  margin-right: 1vw;
}
.check {
  width: 90px;
  height: 40px;
  border: 1px solid #d3cdcd;
  border-radius: 5px;
  padding: 8px 0 0 7px;
}
.c2_button {
  height: 25px;
  margin: 8px 5px 0 35px;
}
.c2_button1 {
  height: 25px;
  margin: 8px 5px 0 0;
}
.date_1 {
  margin: 3px 6px 0 0;
}
.footView span {
  float: left;
  margin-right: 48px;
  line-height: 6vh;
  font-size: 14px;
}
.footView span i {
  margin-right: 5px;
}
.print {
  width: 264px;
  height: 120px;
  background: white;
  position: absolute;
  top: 26%;
  left: 37%;
  z-index: 2;
  padding: 10px 15px;
  box-shadow: 3px 3px 3px #f4f4f4;
}
.print div:first-child {
  font-weight: 700;
  margin-bottom: 5px;
}
.print div:last-child {
  float: right;
  margin: 10px 0 0 0;
}
#createImg {
  margin-top: 200px;
}
</style>

<style>
.clientReturn .el-input__icon {
  line-height: 30px;
}
.clientReturn .clientReturn_top .sty .el-input__inner,
.clientReturn .content1_1 .el-select .el-input__inner {
  height: 30px;
  width: 4.5vw;
}
.clientReturn .clientReturn_top .sty1 .el-input__inner {
  height: 30px;
  width: 8vw;
}
.clientReturn .clientReturn_top .ph .el-input__inner {
  height: 30px;
  width: 8vw;
}
.clientReturn .el-date-editor .el-input__inner {
  padding-right: 0;
}
.clientReturn .el-date-editor {
  width: 8vw;
}
.clientReturn .c_b .el-button {
  padding: 0;
}
.clientReturn .content1_1 > .el-input {
  width: 10vw;
}
.clientReturn .content1_1 .el-input__inner {
  height: 30px;
}
.clientReturn .c2_2 .check {
  margin: 0 16px 0 0;
  width: 70px;
  height: 30px;
  padding: 3px 0 0 7px;
}

.clientReturn .c2_2 .el-button {
  width: 40px;
}
.clientReturn .c2 .el-button {
  margin: 0 10px 0 0;
}
.clientReturn .print .el-radio {
  margin-right: 19px;
}
.clientReturn .el-input-group__append {
  background-color: #ecf5ff;
  color: #409eff;
}

.clientReturn .el-table__footer td {
  height: 26px;
}

.clientReturn .el-table .cell {
  padding: 0 0 0 5px;
}
</style>

<template>
  <div class="clientReturn">
    <div class="clientReturn_top">
      <p class="t_content1">退货日期</p>
      <div class="ph">
        <el-date-picker
          clearable
          v-model="inputDate"
          type="date"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期"
          disabled
        ></el-date-picker>
      </div>
      <p class="t_content">客户编号</p>
      <!-- <input class="inp inp3" type="text" v-model="customerNo" @blur="customerNoBlur" :disabled="jxAgent"> -->
      <div class="sty1">
        <el-select
          filterable
          v-model="customerName"
          @change="
            (e) => {
              ;(this.customerNo = e), (this.printVendor = e)
              this.getCustomerDiscount()
            }
          "
          :disabled="jxAgent"
        >
          <el-option
            v-for="item in customerList"
            :key="item.value"
            :label="item.value + '  ' + item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <p class="t_content">单号</p>
      <input class="inp inp2" type="text" v-model="inputSequence" disabled />
      <!-- <p class="t_content">客退序号</p>
      <input class="inp inp2" type="text" v-model="sequence"> -->
      <p class="t_content">仓库</p>
      <input
        class="inp inp3"
        type="text"
        v-model="warehouseNo"
        @blur="warehouseNoBlur"
        disabled
      />
      <div class="sty">
        <el-select
          v-model="warehouseName"
          @change="
            (e) => {
              this.warehouseNo = e
            }
          "
          disabled
        >
          <el-option
            v-for="item in warehouseNameList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left">{{ item.value }}</span>
            <span style="float: right">{{ item.label }}</span></el-option
          >
        </el-select>
      </div>
      <p class="t_content">折数</p>
      <input class="inp inp2" type="text" v-model="discount" />
      <p class="t_content">配货方式</p>
      <div class="ph">
        <el-select v-model="cooperateWay">
          <el-option
            v-for="item in cooperateWayList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <p class="t_content">备注</p>
      <input class="inp inp2" type="text" v-model="remark" />
      <!-- <p class="t_content a_color hand" @click="modification">修改</p> -->
    </div>
    <div class="clientReturn_c">
      <div class="content1">
        <div class="content1_1">
          <el-select
            v-model="reader"
            style="margin-right: 0.5vw"
            @change="readerChange"
          >
            <el-option
              v-for="item in readerList"
              :key="item.equipmentCabinetNo"
              :label="item.equipmentCabinetNo"
              :value="item.equipmentCabinetNo"
            ></el-option>
          </el-select>
          <el-button @click="readRFID" icon="el-icon-c-scale-to-original">
            读卡</el-button
          >
          <el-button @click="subtractClick">
            <i class="el-icon-remove-outline"></i>减标</el-button
          >
          <el-button @click="emptyClick" style="margin-right: 10px">
            <i class="el-icon-delete"></i>清空</el-button
          >
          <el-input v-model="searchRFID">
            <el-button @click="search" slot="append" style="width: 60px"
              >寻标</el-button
            ></el-input
          >
        </div>
        <div class="c_tab">
          <el-table
            :data="rfidListTable"
            ref="table1"
            style="width: 100%"
            highlight-current-row
            height="81vh"
            :header-cell-style="{
              background: '#f4f4f4',
              padding: 0,
              height: '30px'
            }"
            :cell-style="{ padding: 0, height: '26px' }"
            @row-click="rowClick"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="50"
              key="index1"
              v-if="!isReading"
            ></el-table-column>
            <el-table-column
              prop="index"
              label="序号"
              width="50"
              key="index2"
              v-if="isReading"
            ></el-table-column>
            <el-table-column prop="showCode" label="RFID"></el-table-column>
            <el-table-column prop="kindsNumber" label="货号"></el-table-column>
            <el-table-column
              prop="sellingPrice"
              label="售价"
              width="100"
            ></el-table-column>
            <el-table-column
              prop="inputType"
              label="入单"
              width="50"
            ></el-table-column>
          </el-table>
        </div>
      </div>
      <div class="content2">
        <div class="c2">
          <div class="c2_1">
            <el-button @click="create" type="primary" icon="el-icon-plus"
              >新建</el-button
            >
            <el-button
              @click="confirm"
              icon="el-icon-circle-check"
              :disabled="isConfirm"
              >确认</el-button
            >
            <el-button @click="exp('客户退货')" icon="el-icon-upload2"
              >导出</el-button
            >
            <!-- <div class="dr">
              <i class="el-icon-download"></i>导入
              <input
                @change="readExcel"
                accept=".xls, .xlsx"
                class="outputlist_upload"
                type="file"
                ref="upload"
              />
            </div> -->
            <el-button size="small" class="a-upload el-icon-download"
              >导入
              <template>
                <input
                  type="file"
                  accept=".xlsx,.xls"
                  @change="handleImportInputClick"
                  class="file"
                  id="file"
                />
              </template>
            </el-button>
            <el-button @click="Print" icon="el-icon-printer">列印</el-button>
            <el-button @click="dele" icon="el-icon-delete" :disabled="isConfirm"
              >删除</el-button
            >
          </div>
          <div class="c2_2">
            <p>数量:{{ inputSum }}</p>
            <p>客退序号:{{ sequence }}</p>
            <el-checkbox class="check" v-model="twoDimensional"
              >二维</el-checkbox
            >
            <!-- <el-button icon="el-icon-arrow-left"></el-button>
            <el-button icon="el-icon-arrow-right"></el-button> -->
          </div>
        </div>
        <div class="content2_1">
          <el-table
            id="outTable"
            :data="switchList"
            style="width: 100%"
            height="81vh"
            ref="table"
            border
            show-summary
            :summary-method="getSummaries"
            highlight-current-row
            :header-cell-style="{
              background: '#f4f4f4',
              padding: 0,
              height: '30px'
            }"
            :cell-style="{ padding: 0, height: '26px' }"
          >
            <el-table-column
              type="index"
              label="序号"
              width="50"
            ></el-table-column>
            <template v-for="i in knhList">
              <el-table-column
                :prop="i.prop"
                :label="i.label"
                :width="i.width"
                :key="i.prop"
                show-overflow-tooltip
              ></el-table-column>
            </template>
          </el-table>
        </div>
      </div>
    </div>
    <!-- <foot-view class="footView">
    <div slot="text">
    <span>数据库：{{jxQuarter}}</span></div>
    </foot-view> -->
    <new-build
      :Str="this.Str"
      :style="{ display: showNew_build }"
      :sendData="sendData"
      :flag="showNew_build"
      :pageSession="pageSession"
      @closeNewCR="
        () => {
          this.showNew_build = 'none'
        }
      "
      @saveNew="saveNew"
      @inpNumChange="
        () => {
          this.inpList = this.getInput()
        }
      "
    ></new-build>
    <!-- 列印 -->
    <div class="print" v-if="showPrint">
      <div>列印方式</div>
      <el-radio v-model="printType" label="1">双打</el-radio>
      <el-radio v-model="printType" label="2">发货单</el-radio>
      <el-radio v-model="printType" label="3">地址</el-radio>
      <div>
        <el-button
          @click="
            () => {
              this.showPrint = false
            }
          "
          >取消</el-button
        >
        <el-button @click="printConfirm" type="primary">确定</el-button>
      </div>
    </div>
    <!-- <print-area v-show=false isInput='退' isVendor="客户" :manufacturerName="printVendorName" :principal="contact" :phone="phone" :address="address" :remark="remark" :inputSequence="sequence" :jxQuarter="jxQuarter" :inputDate="printDate" :printTotal="printTotal" :printMoney="printMoney" :printStyle="printStyle" :printSellingPrice="printSellingPrice" :printType="printType" :shipType="cooperateWay" :cellphone="cellphone" :companyName="companyName" :companyPhone="companyPhone"></print-area> -->
    <div id="p" v-show="false"></div>
  </div>
</template>

<script>
const resources = require('../../../config/printCSS')

import footView from '../../../components/FootView'
import newBuild from './childComp/new_Build'
import printArea from '../../../components/PrintVendorStock'

import { getClient } from '../../../network/client'
import { getWarehouse } from '../../../network/warehouse'
import {
  rfidOut,
  outSubtract,
  outEmpty,
  affirmOut,
  getOutInquire,
  outByKindsNumberContinue,
  kindsNumberOut,
  importCustomerOut
} from '../../../network/customerOutTotal'
import {
  connectStatus,
  UHFConnection,
  sendOrder,
  orderList,
  close
} from '../../../network/rfid'
import { getSystemConfig } from '../../../network/operatoryCommand'
import { getUhfTest } from '../../../network/rfid'
import { internetProtocol } from '../../../config/ip'
import { RfidList } from '../../../network/customerInputTotal'

import today from '../../../components/mixins/today'
import enterUp from '../../../components/mixins/enterUp'
import exportMethods from '../../../components/mixins/exportMethods'
import cookieFn from '../../../components/mixins/cookieFn'

import { importExcel } from '@/util/dealWithExcel'

import XLSX from 'xlsx'
import outex from '../../../components/mixins/outexp'
import QRCode from 'qrcode'

export default {
  name: 'client_return_mn',
  mixins: [today, enterUp, exportMethods, outex, cookieFn],
  created() {
    this.inpList = this.getInput()
    // 随机数赋值
    this.pageSession = Math.ceil(Math.random() * 1000000) + ''

    this.knhList = this.knhList1

    // 获取所有客户信息
    this.customerList = []
    getClient({ limit: 99999 }).then((res) => {
      if (res.data.code == 200) {
        let list = res.data.data
        list.forEach((e) => {
          if (e.stop != 1) {
            this.customerList.push({ value: e.no, label: e.name })
          }
        })
        if (this.jxAgent) {
          for (const i of this.customerList) {
            if (i.label == this.operator) {
              this.customerNo = i.value
              this.customerName = i.value
              break
            }
          }
        }
        this.newSend()
      }
      if (this.$route.query.oid) {
        let min =
          new Date().getMinutes() < 10
            ? '0' + new Date().getMinutes()
            : new Date().getMinutes()
        let sec =
          new Date().getSeconds() < 10
            ? '0' + new Date().getSeconds()
            : new Date().getSeconds()
        console.log(this.strRandom + min + sec) //随机字符串加时间      不重复随机字符串
        this.Str = this.strRandom + min + sec

        this.sequence = this.$route.query.oid
        this.getData(true)
        if (this.$route.query.type == 0) {
          this.showNew_build = 'block'
        }
      }
    })
    // 获取仓库信息
    getWarehouse().then((res) => {
      if (res.data.code != 200) return
      let list = res.data.data
      list.sort((a, b) => {
        return a.no.localeCompare(b.no)
      })
      list.forEach((e) => {
        this.warehouseNameList.push({ value: e.no, label: e.name })
        if (e.isMainWarehouse) {
          this.warehouseNo = e.no
          this.warehouseName = e.name
        }
      })
      this.newSend()
    })

    getSystemConfig().then((res) => {
      if (res.data.data) {
        this.companyName = res.data.data.companyName
        this.companyPhone = res.data.data.phone
      }
    })

    getUhfTest().then((res) => {
      this.readerList = res.data.data || []
      this.reader = this.getCookie('RFIDreader') || ''
    })
  },
  data() {
    return {
      Str: '',
      strRandom: Math.random().toString(36).substring(2, 7), //随机字符串
      loading: {},
      isReading: false,
      RFIDflag: 1,
      command: '',
      inpList: [],
      socketId: '',
      ws: {},

      readOnly: false,

      sequence: '',
      pageSession: '',

      originalData: {},

      // 读卡几个
      inputSum: 0,

      pageSession: '',
      showNew_build: 'none',
      showNew_vr: 'none',
      showPopup: 'none',
      inputDate: new Date(),
      customerNo: '',
      customerName: '',
      customerList: [],
      inputSequence: '',
      warehouseNo: '',
      warehouseName: '',
      warehouseNameList: [],
      discount: 10,
      cooperateWay: '配货',
      cooperateWayList: [
        { value: '配货', label: '配货' },
        { value: '订货', label: '订货' },
        { value: '订断', label: '订断' },
        { value: '追断', label: '追断' }
      ],
      remark: '',

      sendData: {},

      searchRFID: '',
      twoDimensional: false,
      rfidList: [],
      efficacious: [],

      rfidListTable: [],
      allRFIDlist: [],
      subRFID: [],

      switchList: [],
      kindsNumberList: [],
      styleNumberList: [],

      knhList: [],
      knhList1: [
        { prop: 'kindsNumber', label: '货号', width: '160' },
        { prop: 'styleNumber', label: '款号', width: '100' },
        { prop: 'colorNo', label: '颜色编号', width: '80' },
        { prop: 'colorName', label: '颜色名称', width: '80' },
        { prop: 'size', label: '尺码', width: '50' },
        { prop: 'sum', label: '数量', width: '80' },
        { prop: 'onePrice', label: '单价', width: '70' },
        { prop: 'money', label: '金额', width: '90' },
        { prop: 'sellingPrice', label: '售价', width: '70' },
        { prop: 'commodityName', label: '品名', width: '160' },
        { prop: 'brandedName', label: '品牌', width: '100' },
        { prop: 'entryTime', label: '录入时间', width: '180' }
      ],
      knhList2: [
        { prop: 'styleNumber', label: '款号', width: '110' },
        { prop: 'colorNoName', label: '颜色', width: '100' },
        { prop: 'c05', label: '05-XS', width: '100' },
        { prop: 'c07', label: '07-S', width: '100' },
        { prop: 'c09', label: '09-M', width: '100' },
        { prop: 'c11', label: '11-L', width: '100' },
        { prop: 'c13', label: '13-XL', width: '100' },
        { prop: 'c15', label: '15-2L', width: '100' },
        { prop: 'c17', label: '17-3L', width: '100' },
        { prop: 'c19', label: '19-4L', width: '100' },
        { prop: 'c21', label: '21-5L', width: '100' },
        { prop: 'c23', label: '23-6L', width: '100' },
        { prop: 'f', label: 'F', width: '100' },
        { prop: 'total', label: '小计', width: '80' },
        { prop: 'sellingPrice', label: '售价', width: '70' },
        { prop: 'sellingPriceMoney', label: '售价金额', width: '100' },
        { prop: 'brandedName', label: '品牌', width: '110' },
        { prop: 'quarter', label: '季度', width: '100' }
      ],

      operator: this.getCookie('jxUser'),
      jxQuarter: this.getCookie('jxQuarter'),
      jxAgent: this.getCookie('jxAgent') == '1',

      showPrint: false,
      printType: '1',

      isConfirm: false,

      // 打印
      styleList: [],
      printTotal: 0,
      printMoney: 0,
      // 款号合计
      printStyle: 0,
      // 售价合计
      printSellingPrice: 0,
      // 客户
      printVendor: '',
      printVendorName: '',
      principal: '',
      contact: '',
      phone: '',
      cellphone: '',
      address: '',
      companyName: '',
      companyPhone: '',
      printDate: this.searchDate(),

      reader: '',
      readerList: []
    }
  },
  watch: {
    twoDimensional(a, b) {
      if (a) {
        this.knhList = this.knhList2
        this.switchList = this.styleNumberList
      } else {
        this.knhList = this.knhList1
        this.switchList = this.kindsNumberList
      }
    },
    // inputDate(a,b){
    //   this.newNo()
    //   this.newSend()
    // },
    customerNo(a, b) {
      this.newNo()
      this.customerNo = a.toUpperCase().trim()
      this.newSend()
    },
    printVendor(a, b) {
      if (!a) return
      getClient({ no: a }).then((res) => {
        this.principal = res.data.data[0].principal || res.data.data[0].name
        this.contact = res.data.data[0].contact || res.data.data[0].name
        this.cellphone = res.data.data[0].phone || ''
        this.phone = res.data.data[0].cellphone || ''
        this.address = res.data.data[0].address || ''
        this.printVendorName = res.data.data[0].no + '_' + res.data.data[0].name
      })
    },
    inputSequence(a, b) {
      this.newNo()
      this.inputSequence = a.toUpperCase().trim()
      this.newSend()
    },
    sequence(a, b) {
      this.newSend()
    },
    warehouseNo(a, b) {
      this.newNo()
      this.newSend()
    },
    discount(a, b) {
      this.newNo()
      this.newSend()
    },
    cooperateWay(a, b) {
      this.newNo()
      this.newSend()
    },
    remark(a, b) {
      this.newNo()
      this.newSend()
    },
    $route(a, b) {
      // console.log(a)
      this.newSend()
      if (b.path.indexOf('delete') != -1) {
        this.newNo()
        return
      }
      if (a.path.indexOf('/customer/client_return_mn') != -1 && a.query.oid) {
        this.inpList = this.getInput()
        this.customerList = []
        this.warehouseNameList = []
        // 获取所有客户信息
        getClient({ limit: 99999 }).then((res) => {
          if (res.data.code == 200) {
            let list = res.data.data
            list.forEach((e) => {
              if (e.stop != 1) {
                this.customerList.push({ value: e.no, label: e.name })
              }
            })
            this.newSend()
          }
          if (this.$route.query.oid) {
            let min =
              new Date().getMinutes() < 10
                ? '0' + new Date().getMinutes()
                : new Date().getMinutes()
            let sec =
              new Date().getSeconds() < 10
                ? '0' + new Date().getSeconds()
                : new Date().getSeconds()
            console.log(this.strRandom + min + sec) //随机字符串加时间      不重复随机字符串
            this.Str = this.strRandom + min + sec

            this.sequence = this.$route.query.oid
            this.getData(true)
            if (this.$route.query.type == 0) {
              this.showNew_build = 'block'
            }
          }
        })
        // 获取仓库信息
        getWarehouse().then((res) => {
          if (res.data.code != 200) return
          let list = res.data.data
          list.sort((a, b) => {
            return a.no.localeCompare(b.no)
          })
          list.forEach((e) => {
            this.warehouseNameList.push({ value: e.no, label: e.name })
            if (e.isMainWarehouse) {
              this.warehouseNo = e.no
              this.warehouseName = e.name
            }
          })
          this.newSend()
        })
      }
    },
    searchRFID(a, b) {
      this.searchRFID = a.toUpperCase().trim()
    }
  },
  components: {
    footView,
    newBuild,
    printArea
  },
  methods: {
    getCustomerDiscount() {
      getClient({ no: this.customerNo }).then((res) => {
        console.log(res)
        if (res.data.data != null) {
          this.discount = res.data.data[0].sellDiscount
        }
      })
    },
    // 数据变动
    newSend() {
      this.sendData = {
        inputDate: this.inputDate,
        customerNo: this.customerNo,
        customerName: this.customerName,
        customerList: this.customerList,
        inputSequence: this.inputSequence,
        sequence: this.sequence,
        warehouseNo: this.warehouseNo,
        warehouseName: this.warehouseName,
        warehouseList: this.warehouseNameList,
        discount: this.discount,
        cooperateWay: this.cooperateWay,
        remark: this.remark,
        isConfirm: this.isConfirm
      }
    },

    // 读卡
    readRFID() {
      this.RFIDflag = 1
      if (!this.inputDate) {
        this.$alert('日期不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.customerNo) {
        this.$alert('客户不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.warehouseNo) {
        this.$alert('仓库不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.discount) {
        this.$alert('折数不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.reader) {
        this.$alert('请选择读卡机', '', {
          confirmButtonText: '确定'
        })
        return
      }

      if (this.isConfirm) this.isConfirm = false
      if (this.readOnly) this.readOnly = false

      let host = ''
      let port = ''
      for (const i of this.readerList) {
        if (this.reader == i.equipmentCabinetNo) {
          this.command = i.testHead + i.testBody
          host = i.ip
          port = i.port
          break
        }
      }
      if (!host) {
        this.$alert('请选择读卡机', '', {
          confirmButtonText: '确定'
        })
        return
      }
      this.$message.info('读卡中...等待过长,重读即可！')

      // socketId赋值
      this.socketId = Math.ceil(Math.random() * 1000000) + ''
      this.ws = new WebSocket(
        `wss://${internetProtocol}/webSocket/${this.socketId}`
      )
      this.ws.onopen = (e) => {
        UHFConnection({
          host,
          port,
          socketId: this.socketId
        })
        setTimeout(() => {
          connectStatus({ socketId: this.socketId }).then((res) => {
            if (res.data.code == 200) {
              this.isReading = true
              this.rfidListTable = []
              if (!this.sequence) {
                this.rfidList = []
              }
              this.switchList = []
              this.efficacious = []
              this.$message.success('读卡器连接成功,开始读卡')
              sendOrder({
                command: this.command,
                connectId: this.socketId
              })
              this.loading = this.$loading({
                lock: true,
                text: '读卡中...',
                spinner: 'el-icon-loading',
                background: 'rgba(255, 255, 255, 0)'
              })
            } else if (res.data.code == 201) {
              this.$message.error('读卡器连接失败')
            } else {
              this.$message.error(res.data.msg)
            }
          })
        }, 1500)
      }
      this.ws.onmessage = (e) => {
        // console.log(e)
        if (e.data == '连接成功') return

        let obj = e.data
        obj = JSON.parse(obj)
        if (obj.endCommand) {
          this.$message.success('读卡完成')
          this.loading.close()
          this.ws.close()
          this.rfidAdd()
        }

        if (obj.isConnectError) {
          // 连接异常
          this.$message.error(
            `请检查路由器外网IP是否与此IP一致 ：${obj.connectTimeOutIp}`
          )
          this.loading.close()
          this.ws.close()
        }

        if (obj.validShowCode) {
          if (this.rfidList.length) {
            let exist = 0
            for (const i of this.rfidList) {
              if (i == obj.validShowCode) {
                exist = 1
                break
              }
            }
            if (!exist) {
              this.rfidList.unshift(obj.validShowCode)
              this.efficacious.push(obj.validShowCode)
            }
          } else {
            this.rfidList.unshift(obj.validShowCode)
            this.efficacious.push(obj.validShowCode)
          }
          this.rfidListTable.unshift({
            showCode: obj.validShowCode,
            index: this.rfidListTable.length + 1
          })
        }
        if (obj.otherErrorRFID) {
          if (this.rfidListTable.length) {
            let exist = 0
            for (const i of this.rfidListTable) {
              if (i.showCode.indexOf(obj.otherErrorRFID) != -1) {
                exist = 1
                break
              }
            }
            if (!exist) {
              this.rfidListTable.unshift({
                showCode: obj.otherErrorRFID + '其他错误',
                index: this.rfidListTable.length + 1
              })
            }
          } else {
            this.rfidListTable.unshift({
              showCode: obj.otherErrorRFID + '其他错误',
              index: this.rfidListTable.length + 1
            })
          }
        }
        if (obj.antennaErrorRFID) {
          if (this.rfidListTable.length) {
            let exist = 0
            for (const i of this.rfidListTable) {
              if (i.showCode.indexOf(obj.antennaErrorRFID) != -1) {
                exist = 1
                break
              }
            }
            if (!exist) {
              this.rfidListTable.unshift({
                showCode:
                  obj.antennaErrorRFID + '天线错误' + obj.antennaErrorIndex,
                index: this.rfidListTable.length + 1
              })
            }
          } else {
            this.rfidListTable.unshift({
              showCode:
                obj.antennaErrorRFID + '天线错误' + obj.antennaErrorIndex,
              index: this.rfidListTable.length + 1
            })
          }
        }
      }
      this.ws.onclose = () => {
        // console.log("调转连接已关闭")
      }
      this.ws.onerror = (e) => {
        console.log(e)
      }
    },
    rfidAdd() {
      if (!this.efficacious.length) {
        this.rfidListTable = this.allRFIDlist
        this.switchList = this.kindsNumberList
        return
      }
      // 是否有信息变动
      let isNew = false

      if (JSON.stringify(this.originalData) == '{}') {
        // 第一次点读卡，记录原始数据
        this.originalData.inputDate = this.inputDate
        this.originalData.customerNo = this.customerNo
        this.originalData.inputSequence = this.inputSequence
        this.originalData.warehouseNo = this.warehouseNo
        this.originalData.discount = this.discount
        this.originalData.cooperateWay = this.cooperateWay
        this.originalData.cooperateSequence = this.cooperateSequence
        this.originalData.remark = this.remark
      } else {
        // 判断是否修改了数据
        for (const key in this.originalData) {
          if (this.originalData.hasOwnProperty(key)) {
            const e = this.originalData[key]
            if (e != this[key]) {
              // 修改了数据 重新赋值
              isNew = true
              this.originalData.inputDate = this.inputDate
              this.originalData.manufacturerNo = this.manufacturerNo
              this.originalData.odd = this.odd
              this.originalData.inputWarehouseNo = this.inputWarehouseNo
              this.originalData.companyNo = this.companyNo
              this.originalData.cooperateWay = this.cooperateWay
              this.originalData.cooperateSequence = this.cooperateSequence
              this.originalData.remark = this.remark
              break
            }
          }
        }
      }

      let validList = []
      if (this.sequence != '' && !isNew) {
        // 有进厂序号并且信息没改，再点读卡，传右表
        // console.log('没有数据变动读卡')
        validList = this.kindsNumberList
      } else {
        // console.log('第一次或有数据变动读卡')
        // 有数据变动，进厂序号改空
        this.sequence = ''
        this.allRFIDlist = []
        this.kindsNumberList = []
      }

      let d = {
        customerDTO: {
          pageSession: this.pageSession,
          inputDate: this.inputDate,
          customerNo: this.customerNo,
          sequence: this.sequence,
          inputSequence: this.inputSequence,
          warehouseNo: this.warehouseNo,
          discount: this.discount,
          cooperateWay: this.cooperateWay,
          remark: this.remark
        },
        rfidShowCodeList: this.efficacious,
        // rfidShowCodeList: this.rfidList,
        validList
      }
      // console.log(d)
      rfidOut(JSON.stringify(d)).then((res) => {
        if (res.data.code == 200 && res.data.data.validList) {
          this.sequence = res.data.data.validList[0]
            ? res.data.data.validList[0].sequence
            : ''

          if (res.data.data.outOfStock && res.data.data.outOfStock.length) {
            // 库存不足导出
            this.exportRaw(String(res.data.data.outOfStock), '库存不足.txt')
          }
          if (
            res.data.data.errorRfidList &&
            res.data.data.errorRfidList.length
          ) {
            // 导出errorRfid
            this.exportRaw(
              String(res.data.data.errorRfidList),
              '库存不足Rfid.txt'
            )
          }
          if (
            res.data.data.outOfStockPlus &&
            res.data.data.outOfStockPlus.length
          ) {
            // 部分成功导出
            this.exportRaw(String(res.data.data.outOfStockPlus), '部分成功.txt')
          }
        }
        if (this.sequence) {
          this.getData(false)
        }
      })
    },
    readerChange(e) {
      this.delCookie('RFIDreader')
      this.setCookie('RFIDreader', e, 365)
    },

    // 减标
    subtractClick() {
      if (!this.sequence) return
      if (!this.subRFID.length) {
        this.$alert('请先点击选择一条数据再进行减标操作', '', {
          confirmButtonText: '确定'
        })
        return
      }

      if (this.subRFID.length == this.rfidListTable.length) {
        this.emptyClick()
        return
      }

      let d = {
        customerDTO: {
          sequence: this.sequence,
          customerNo: this.customerNo,
          warehouseNo: this.warehouseNo
        },
        rfidList: this.subRFID
      }

      // console.log(d)
      outSubtract(JSON.stringify(d)).then((res) => {
        // console.log(res)
        if (res.data.code == 200) {
          this.getData(false)
          this.$message({
            message: '减标成功',
            type: 'success'
          })
          this.subRFID = []
        } else {
          this.$message.error('减标失败')
        }
      })
    },
    // 清空
    emptyClick() {
      if (!this.sequence) {
        this.$message.info(`已清空`)
        return
      }
      outEmpty({
        sequence: this.sequence,
        customerNo: this.customerNo,
        warehouseNo: this.warehouseNo
      }).then((res) => {
        if (res.data.code == 200) {
          this.sequence = ''
          this.inputSum = 0

          // 左表清空
          this.rfidListTable = []
          this.allRFIDlist = []
          this.rfidList = []

          // 右表清空
          this.switchList = []
          this.kindsNumberList = []
          this.styleNumberList = []

          this.inputSum = 0
          this.$message({
            message: '清空成功',
            type: 'success'
          })
        } else {
          this.$message.error('清空失败')
        }
      })
    },
    // 寻标
    search() {
      if (this.searchRFID) {
        let exist = 0
        for (const i of this.allRFIDlist) {
          if (this.searchRFID == i.showCode) {
            this.$refs.table1.setCurrentRow(i)
            this.subRFID = [i]
            exist = 1
            break
          }
        }
        // console.log(this.subRFID)
        if (!exist) {
          this.$message.error(`RFID${this.searchRFID}不存在`)
        }
      }
    },
    // 确认
    confirm() {
      if (!this.sequence) return
      let d = {
        customerDTO: {
          inputDate: this.inputDate,
          customerNo: this.customerNo,
          inputSequence: this.inputSequence,
          sequence: this.sequence,
          warehouseNo: this.warehouseNo,
          discount: this.discount,
          cooperateWay: this.cooperateWay,
          remark: this.remark
        },
        validList: this.kindsNumberList
      }
      affirmOut(JSON.stringify(d)).then((res) => {
        if (res.data.code == 200) {
          this.$message({
            message: '确认成功',
            type: 'success'
          })
          this.isConfirm = true
        } else {
          this.$message.error('确认失败')
        }
      })
    },

    dele() {
      if (!this.sequence) return
      this.$router.push({
        path: '/delete_document',
        query: { type: 4, sequence: this.sequence }
      })
      this.$store.commit('addNav', {
        label: '客户退货删单',
        name: 'delete_document'
      })
    },

    create() {
      this.showNew_build = 'block'
      if (!this.$route.query.oid) {
        if (this.isConfirm) this.isConfirm = false
        if (this.readOnly) this.readOnly = false
        this.sequence = ''
        this.inputSum = 0
        this.rfidListTable = []
        this.allRFIDlist = []
        this.switchList = []
        this.kindsNumberList = []
        this.styleNumberList = []
      }
    },

    saveNew(res) {
      this.isConfirm = false
      this.readOnly = true

      if (res.sequence) {
        this.sequence = res.sequence
        this.getData(true)
      }
    },

    // 列印
    Print() {
      if (!this.styleNumberList.length) {
        this.$message.info('暂无数据')
        return
      }
      this.showPrint = true
      this.styleList = []
      this.printTotal = 0
      this.printMoney = 0
      this.printStyle = 0
      this.printSellingPrice = 0
    },
    printConfirm() {
      // console.log('点击确定了')
      this.showPrint = false
      let printArea = document.getElementById('p')

      if (this.printType != '3') {
        printArea.innerHTML = `
          <div style="margin-top: 20px;">
            <p class="rightTag" style="top: 3cm;">白联仓库 红联财务 黄联客户</p>
            <span class="printHead">
              ${this.companyName}${this.jxQuarter}客户退货单
            </span>
            <div class="qrInfo" style="height: 25px;">
              <p style="margin: 5px 0;">客户：${this.printVendorName}</p>
              <p style="margin: 5px 0;">联系人：${this.contact}</p>
              <p style="margin: 5px 0;">退货序号：${this.sequence}</p>
            </div>
            <div class="qrInfo" style="height: 25px;">
              <p style="margin: 5px 0;">客户电话：${this.phone}</p>
              <p style="margin: 5px 0;">出货类型：${this.cooperateWay}</p>
              <p style="margin: 5px 0;">退货日期：${this.inputDate.slice(
                0,
                10
              )}</p>
            </div>
            <canvas id="canvas"></canvas>
          </div>
          
          <table 
            border="1" 
            align="center" 
            id="printTable">
            <thead>
              <tr>
                <td style="width: 4%;padding: 0;" rowspan="2">序号</td>
                <td style="width: 15%;padding: 0;" rowspan="2">型色</td>
                <td style="width: 8%;padding: 0;" rowspan="2">颜色</td>
                <td style="width: 15%;padding: 0;" rowspan="2">品名</td>
                <td style="width: 3.8%;padding: 0;" nowrap="nowrap">05</td>
                <td style="width: 3.8%;padding: 0;" nowrap="nowrap">07</td>
                <td style="width: 3.8%;padding: 0;" nowrap="nowrap">09</td>
                <td style="width: 3.8%;padding: 0;" nowrap="nowrap">11</td>
                <td style="width: 3.8%;padding: 0;" nowrap="nowrap">13</td>
                <td style="width: 3.8%;padding: 0;" nowrap="nowrap">15</td>
                <td style="width: 3.8%;padding: 0;" nowrap="nowrap">17</td>
                <td style="width: 3.8%;padding: 0;" nowrap="nowrap">19</td>
                <td style="width: 3.8%;padding: 0;" nowrap="nowrap">21</td>
                <td style="width: 3.8%;padding: 0;" nowrap="nowrap">23</td>
                <td style="width: 3.8%;padding: 0;">F</td>
                <td rowspan="2" style="width: 5%;">数量</td>
                <td rowspan="2" style="width: 5%;">单价</td>
                <td rowspan="2">金额</td>
              </tr>
              <tr>
                <td style="border-top: 1px dotted;border-left: 1px dotted;">XS</td>
                <td style="border-top: 1px dotted;">S</td>
                <td style="border-top: 1px dotted;">M</td>
                <td style="border-top: 1px dotted;">L</td>
                <td style="border-top: 1px dotted;">XL</td>
                <td style="border-top: 1px dotted;">2L</td>
                <td style="border-top: 1px dotted;">3L</td>
                <td style="border-top: 1px dotted;">4L</td>
                <td style="border-top: 1px dotted;">5L</td>
                <td style="border-top: 1px dotted;">6L</td>
                <td style="border-top: 1px dotted;"></td>
              </tr>
            </thead>
          </table>
        `
        this.$confirm('是否使用A4纸打印', '提示', {
          distinguishCancelAndClose: true,
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        })
          .then(() => {
            // 用A4纸
            // console.log('用A4纸')
            this.openPrint(true)
          })
          .catch((action) => {
            // 用半张A4纸
            if (action == 'cancel') {
              // console.log('用半张A4纸')
              this.openPrint(false)
            }
          })
      } else {
        printArea.innerHTML = `
          <div id="printA">
            <div class="addressH1">
              <p>收货地址：${this.address}</p>
            </div>
            <div class="addressH1">
              <p>收货人：${this.printVendorName.split('_')[1]}</p>
            </div>
            <div class="addressH1">
              <p>电话：${this.cellphone}</p>
            </div>
            <div class="addressH1">
              <p>手机：${this.phone}</p>
            </div>
            <div class="addressH2">
              <p>寄件人：${this.companyName}</p>
              <p>联系电话：${this.companyPhone}</p>
            </div>
            <div class="addressH2">
              <p>备注：${this.remark || ''}</p>
            </div>
            <div class="addressH2">
              <p>单据类型：${this.cooperateWay}</p>
              <p>单据序号：${this.inputSequence}</p>
              <p>${this.printStyle}</p>
            </div>
            <div class="addressH2">
              <p>制单人：${this.operator}</p>
              <p>${this.inputDate}</p>
            </div>
          </div>
        `
        this.styleNumberList.forEach((e) => {
          this.printStyleCount(e.styleNumber)
        })
        this.printStyle = this.styleList.length
        let int = setInterval(() => {
          if (this.printStyle) {
            clearInterval(int)
            let printHtml = document.getElementById('p').innerHTML
            let wind = window.open(
              '',
              'newwindow',
              'height=500, width=1000, top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no'
            )
            wind.document.body.innerHTML = printHtml
            let style = document.createElement('style')
            style.type = 'text/css'
            style.innerHTML = resources.printCSS
            wind.document.head.appendChild(style)
            wind.print()
          }
        }, 100)
      }
    },
    openPrint(isA4, x = 1, id = 'printTable') {
      let index = --x
      let printTable = document.getElementById(id)
      let length = this.styleNumberList.length

      for (index; index < length; index++) {
        const e = this.styleNumberList[index]
        // console.log(index)
        // console.log(index+1)
        this.printTotal += e.total
        this.printMoney += Number(e.money)
        this.printSellingPrice += Number(e.sellingPriceMoney)

        let row = printTable.insertRow(printTable.FetchRowCount)
        row.insertCell(0).innerHTML = index + 1
        row.insertCell(1).innerHTML = e.styleNumber + '-' + e.colorNo
        row.insertCell(2).innerHTML = e.colorName
        row.insertCell(3).innerHTML = e.commodityName
        row.insertCell(4).innerHTML = e.c05
        row.insertCell(5).innerHTML = e.c07
        row.insertCell(6).innerHTML = e.c09
        row.insertCell(7).innerHTML = e.c11
        row.insertCell(8).innerHTML = e.c13
        row.insertCell(9).innerHTML = e.c15
        row.insertCell(10).innerHTML = e.c17
        row.insertCell(11).innerHTML = e.c19
        row.insertCell(12).innerHTML = e.c21
        row.insertCell(13).innerHTML = e.c23
        row.insertCell(14).innerHTML = e.f
        row.insertCell(15).innerHTML = e.total
        row.insertCell(16).innerHTML = e.onePrice
        row.insertCell(17).innerHTML = e.money

        if (isA4) {
          if (
            parseInt((index + 1) / 33) &&
            (index + 1) % 33 == 0 &&
            index + 1 != length
          ) {
            // console.log('33倍数')
            let pageIndex = index + 3 - parseInt(index / 33) * 33
            // console.log(pageIndex)
            // console.log(index+1)    // 33
            // console.log(length)     // 36
            let startingPoint = index - 32
            let pageTotal = 0
            let pageMoney = 0
            for (let j = startingPoint; j <= index; j++) {
              pageTotal += this.styleNumberList[j].total
              pageMoney += Number(this.styleNumberList[j].sellingPriceMoney)
            }

            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '本页小计：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = pageTotal
            printTable.rows[pageIndex].cells[1].colSpan = '2'
            rowEnd.insertCell(2).innerHTML = '汇总金额：'
            printTable.rows[pageIndex].cells[2].colSpan = '4'
            rowEnd.insertCell(3).innerHTML = pageMoney.toFixed(2)
            printTable.rows[pageIndex].cells[3].colSpan = '10'

            let newHead = document.createElement('div')
            newHead.classList.add('addPrintHead')
            newHead.innerHTML = `
              <p class="rightTag" style="top: ${
                ((index + 1) / 33) * 29.7 + 3
              }cm;">白联仓库 红联财务 黄联客户</p>
              <span class="printHead">
                ${this.companyName}${this.jxQuarter}客户退货单
              </span>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">客户：${this.printVendorName}</p>
                <p style="margin: 5px 0;">联系人：${this.contact}</p>
                <p style="margin: 5px 0;">退货序号：${this.sequence}</p>
              </div>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">客户电话：${this.phone}</p>
                <p style="margin: 5px 0;">出货类型：${this.cooperateWay}</p>
                <p style="margin: 5px 0;">退货日期：${this.printDate.slice(
                  0,
                  10
                )}</p>
              </div>
            `
            newHead.style.pageBreakBefore = 'always'
            this.insertAfter(newHead, printTable)

            let tableId = `printTable${(index + 1) / 33}`
            // console.log(tableId)
            let tableDom = document.createElement('table')
            tableDom.border = '1'
            tableDom.align = 'center'
            tableDom.id = tableId
            tableDom.innerHTML = `
              <thead>
                <tr>
                  <td style="width: 4%;padding: 0;" rowspan="2">序号</td>
                  <td style="width: 15%;padding: 0;" rowspan="2">型色</td>
                  <td style="width: 8%;padding: 0;" rowspan="2">颜色</td>
                  <td style="width: 15%;padding: 0;" rowspan="2">品名</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">05</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">07</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">09</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">11</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">13</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">15</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">17</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">19</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">21</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">23</td>
                  <td style="width: 3.8%;padding: 0;">F</td>
                  <td rowspan="2" style="width: 5%;">数量</td>
                  <td rowspan="2" style="width: 5%;">单价</td>
                  <td rowspan="2">金额</td>
                </tr>
                <tr>
                  <td style="border-top: 1px dotted;border-left: 1px dotted;">XS</td>
                  <td style="border-top: 1px dotted;">S</td>
                  <td style="border-top: 1px dotted;">M</td>
                  <td style="border-top: 1px dotted;">L</td>
                  <td style="border-top: 1px dotted;">XL</td>
                  <td style="border-top: 1px dotted;">2L</td>
                  <td style="border-top: 1px dotted;">3L</td>
                  <td style="border-top: 1px dotted;">4L</td>
                  <td style="border-top: 1px dotted;">5L</td>
                  <td style="border-top: 1px dotted;">6L</td>
                  <td style="border-top: 1px dotted;"></td>
                </tr>
              </thead>
            `
            // console.log(tableDom)
            // console.log(index)
            this.printStyleCount(e.styleNumber)
            this.insertAfter(tableDom, newHead)
            this.openPrint(true, index + 2, tableId)
            return
          }
          if (index + 1 == length) {
            let pageIndex = index + 3 - parseInt(index / 33) * 33
            // console.log('最后一行')
            let startingPoint = index < 33 ? 0 : parseInt(index / 33) * 33
            let pageTotal = 0
            let pageMoney = 0
            for (let j = startingPoint; j <= index; j++) {
              pageTotal += this.styleNumberList[j].total
              pageMoney += Number(this.styleNumberList[j].sellingPriceMoney)
            }
            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '本页小计：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = pageTotal
            printTable.rows[pageIndex].cells[1].colSpan = '2'
            rowEnd.insertCell(2).innerHTML = '汇总金额：'
            printTable.rows[pageIndex].cells[2].colSpan = '4'
            rowEnd.insertCell(3).innerHTML = pageMoney.toFixed(2)
            printTable.rows[pageIndex].cells[3].colSpan = '10'
          }
        } else {
          if (
            parseInt((index + 1) / 12) &&
            (index + 1) % 12 == 0 &&
            index + 1 != length
          ) {
            // console.log('12倍数')
            let pageIndex = index + 3 - parseInt(index / 12) * 12
            // console.log(pageIndex)
            // console.log(index+1)    // 12
            // console.log(length)     // 36
            let startingPoint = index - 11
            let pageTotal = 0
            let pageMoney = 0
            for (let j = startingPoint; j <= index; j++) {
              pageTotal += this.styleNumberList[j].total
              pageMoney += Number(this.styleNumberList[j].sellingPriceMoney)
            }

            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '本页小计：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = pageTotal
            printTable.rows[pageIndex].cells[1].colSpan = '2'
            rowEnd.insertCell(2).innerHTML = '汇总金额：'
            printTable.rows[pageIndex].cells[2].colSpan = '4'
            rowEnd.insertCell(3).innerHTML = pageMoney.toFixed(2)
            printTable.rows[pageIndex].cells[3].colSpan = '10'

            let newHead = document.createElement('div')
            newHead.classList.add('addPrintHead')
            newHead.innerHTML = `
              <p class="rightTag" style="top: ${
                ((index + 1) / 12) * 14.85 + 3
              }cm;">白联仓库 红联财务 黄联客户</p>
              <span class="printHead">
                ${this.companyName}${this.jxQuarter}客户退货单
              </span>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">客户：${this.printVendorName}</p>
                <p style="margin: 5px 0;">联系人：${this.contact}</p>
                <p style="margin: 5px 0;">退货序号：${this.sequence}</p>
              </div>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">客户电话：${this.phone}</p>
                <p style="margin: 5px 0;">出货类型：${this.cooperateWay}</p>
                <p style="margin: 5px 0;">退货日期：${this.printDate.slice(
                  0,
                  10
                )}</p>
              </div>
            `
            newHead.style.pageBreakBefore = 'always'
            this.insertAfter(newHead, printTable)

            let tableId = `printTable${(index + 1) / 12}`
            // console.log(tableId)
            let tableDom = document.createElement('table')
            tableDom.border = '1'
            tableDom.align = 'center'
            tableDom.id = tableId
            tableDom.innerHTML = `
              <thead>
                <tr>
                  <td style="width: 4%;padding: 0;" rowspan="2">序号</td>
                  <td style="width: 15%;padding: 0;" rowspan="2">型色</td>
                  <td style="width: 8%;padding: 0;" rowspan="2">颜色</td>
                  <td style="width: 15%;padding: 0;" rowspan="2">品名</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">05</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">07</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">09</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">11</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">13</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">15</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">17</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">19</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">21</td>
                  <td style="width: 3.8%;padding: 0;" nowrap="nowrap">23</td>
                  <td style="width: 3.8%;padding: 0;">F</td>
                  <td rowspan="2" style="width: 5%;">数量</td>
                  <td rowspan="2" style="width: 5%;">单价</td>
                  <td rowspan="2">金额</td>
                </tr>
                <tr>
                  <td style="border-top: 1px dotted;border-left: 1px dotted;">XS</td>
                  <td style="border-top: 1px dotted;">S</td>
                  <td style="border-top: 1px dotted;">M</td>
                  <td style="border-top: 1px dotted;">L</td>
                  <td style="border-top: 1px dotted;">XL</td>
                  <td style="border-top: 1px dotted;">2L</td>
                  <td style="border-top: 1px dotted;">3L</td>
                  <td style="border-top: 1px dotted;">4L</td>
                  <td style="border-top: 1px dotted;">5L</td>
                  <td style="border-top: 1px dotted;">6L</td>
                  <td style="border-top: 1px dotted;"></td>
                </tr>
              </thead>
            `
            // console.log(tableDom)
            // console.log(index)
            this.printStyleCount(e.styleNumber)
            this.insertAfter(tableDom, newHead)
            this.openPrint(false, index + 2, tableId)
            return
          }
          if (index + 1 == length) {
            let pageIndex = index + 3 - parseInt(index / 12) * 12
            // console.log('最后一行')
            let startingPoint = index < 12 ? 0 : parseInt(index / 12) * 12
            let pageTotal = 0
            let pageMoney = 0
            for (let j = startingPoint; j <= index; j++) {
              pageTotal += this.styleNumberList[j].total
              pageMoney += Number(this.styleNumberList[j].sellingPriceMoney)
            }
            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '本页小计：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = pageTotal
            printTable.rows[pageIndex].cells[1].colSpan = '2'
            rowEnd.insertCell(2).innerHTML = '汇总金额：'
            printTable.rows[pageIndex].cells[2].colSpan = '4'
            rowEnd.insertCell(3).innerHTML = pageMoney.toFixed(2)
            printTable.rows[pageIndex].cells[3].colSpan = '10'
          }
        }

        this.printStyleCount(e.styleNumber)
      }

      this.printStyle = this.styleList.length
      // console.log(this.styleList)

      let int = setInterval(() => {
        if (this.printStyle) {
          clearInterval(int)
          let printArea = document.getElementById('p')
          let footBox = document.createElement('div')
          footBox.innerHTML = `
            <div class="info">
              <p style="margin: 5px 0;">款号合计：${this.printStyle}</p>
              <p style="margin: 5px 0;">售价合计：${this.printSellingPrice.toFixed(
                2
              )}</p>
              <p style="margin: 5px 0;">数量合计：${this.printTotal}</p>
              <p style="margin: 5px 0;">金额合计：${this.printMoney.toFixed(
                2
              )}</p>
            </div>
            <div class="info">
              <p style="margin: 5px 0;">操作员：${this.operator}</p>
              <p style="margin: 5px 0;">财务：</p>
              <p style="margin: 5px 0;">复核：</p>
              <p style="margin: 5px 28.7vw 5px 0;">备注：</p>
            </div>
          `
          printArea.appendChild(footBox)
          if (this.printType == '1') {
            let addressBox = document.createElement('div')
            addressBox.innerHTML = `
              <div id="printA">
                <div class="addressH1">
                  <p>收货地址：${this.address}</p>
                </div>
                <div class="addressH1">
                  <p>收货人：${this.printVendorName.split('_')[1]}</p>
                </div>
                <div class="addressH1">
                  <p>电话：${this.cellphone}</p>
                </div>
                <div class="addressH1">
                  <p>手机：${this.phone}</p>
                </div>
                <div class="addressH2">
                  <p>寄件人：${this.companyName}</p>
                  <p>联系电话：${this.companyPhone}</p>
                </div>
                <div class="addressH2">
                  <p>备注：${this.remark || ''}</p>
                </div>
                <div class="addressH2">
                  <p>单据类型：${this.cooperateWay}</p>
                  <p>单据序号：${this.inputSequence}</p>
                  <p>${this.printStyle}</p>
                </div>
                <div class="addressH2">
                  <p>制单人：${this.operator}</p>
                  <p>${this.inputDate}</p>
                </div>
              </div>
            `
            addressBox.style.pageBreakBefore = 'always'
            printArea.appendChild(addressBox)
          }
          let printHtml = printArea.innerHTML
          let wind = window.open(
            '',
            'newwindow',
            'height=500, width=1000, top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no'
          )
          wind.document.body.innerHTML = printHtml
          let style = document.createElement('style')
          style.type = 'text/css'
          style.innerHTML = resources.printCSS
          wind.document.head.appendChild(style)
          this.$forceUpdate()
          QRCode.toCanvas(
            wind.document.getElementById('canvas'),
            '2' + this.sequence,
            {
              errorCorrectionLevel: 'low',
              width: 90,
              margin: 0,
              quality: 0.3,
              scale: 1
            },
            (error) => {
              if (error) throw error
              wind.print()
            }
          )
          return false
        }
      }, 500)
    },
    printStyleCount(s) {
      if (!this.styleList.length) {
        this.styleList.push(s)
      } else {
        let exist = 0
        for (const i of this.styleList) {
          // console.log(i)
          if (i == s) {
            exist = 1
            break
          }
        }
        if (!exist) {
          this.styleList.push(s)
        }
      }
    },
    // insertAfter(p,header1) // 因为js没有直接追加到指定元素后面的方法 所以要自己创建一个方法
    insertAfter(newElement, targetElement) {
      // newElement是要追加的元素 targetElement 是指定元素的位置
      let parent = targetElement.parentNode // 找到指定元素的父节点
      if (parent.lastChild == targetElement) {
        // 判断指定元素的是否是节点中的最后一个位置 如果是的话就直接使用appendChild方法
        parent.appendChild(newElement, targetElement)
      } else {
        parent.insertBefore(newElement, targetElement.nextSibling)
      }
    },

    // 客户编号失去焦点
    customerNoBlur() {
      if (this.customerNo != '') {
        for (const i of this.customerList) {
          if (this.customerNo == i.value) {
            this.customerName = i.label
            this.printVendor = this.customerNo
            return
          }
        }
        this.$alert('无此客户编号', '', {
          confirmButtonText: '确定'
        })
        this.printVendor = ''
        this.customerNo = ''
        this.customerName = ''
      } else {
        this.printVendor = ''
        this.customerName = ''
      }
    },
    // 仓库编号失去焦点
    warehouseNoBlur() {
      if (this.warehouseNo != '') {
        for (const i of this.warehouseNameList) {
          if (this.warehouseNo == i.value) {
            this.warehouseName = i.label
            return
          }
        }
        this.$alert('无此仓库编号', '', {
          confirmButtonText: '确定'
        })
        this.warehouseNo = ''
        this.warehouseName = ''
      } else {
        this.warehouseName = ''
      }
    },

    rowClick(row, column, event) {
      this.subRFID = [row]
    },
    handleSelectionChange(val) {
      this.subRFID = val
    },
    async handleImportInputClick(evt) {
      const params = {
        no: '客户编号',
        warehouseNo: '仓库编号',
        kindsNumber: '货号',
        number: '数量'
      }
      const dataList = await importExcel(evt, params)
      const { data } = await importCustomerOut(dataList)
      if (data && data.code === 200 && data.data) {
        this.$message.success(data.msg)
        this.switchList = data.data.validList || []
      }
    },
    // readExcel(e) {
    //   if (!this.inputDate) {
    //     this.$alert('日期不能为空', '', {
    //       confirmButtonText: '确定'
    //     })
    //     return
    //   }
    //   if (!this.customerNo) {
    //     this.$alert('客户不能为空', '', {
    //       confirmButtonText: '确定'
    //     })
    //     return
    //   }
    //   if (!this.warehouseNo) {
    //     this.$alert('仓库不能为空', '', {
    //       confirmButtonText: '确定'
    //     })
    //     return
    //   }
    //   if (!this.discount) {
    //     this.$alert('折数不能为空', '', {
    //       confirmButtonText: '确定'
    //     })
    //     return
    //   }

    //   const files = e.target.files
    //   // console.log(files)
    //   if (files.length <= 0) {
    //     //如果没有文件名
    //     return false
    //   } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
    //     this.$Message.error('上传格式不正确，请上传xls或者xlsx格式')
    //     return false
    //   }

    //   const fileReader = new FileReader()
    //   fileReader.onload = (ev) => {
    //     // console.log(ev)
    //     try {
    //       const data = ev.target.result
    //       const workbook = XLSX.read(data, {
    //         type: 'binary'
    //       })
    //       const wsname = workbook.SheetNames[0] //取第一张表
    //       const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) //生成json表格内容
    //       // console.log(ws)
    //       // return

    //       let kindsNumberNumMap = {}
    //       ws.forEach((e) => {
    //         kindsNumberNumMap[e.货号.toString().toUpperCase().trim()] = e.数量
    //       })

    //       // 是否有信息变动
    //       let isNew = false

    //       if (JSON.stringify(this.originalData) == '{}') {
    //         // 第一次点读卡，记录原始数据
    //         this.originalData.inputDate = this.inputDate
    //         this.originalData.customerNo = this.customerNo
    //         this.originalData.inputSequence = this.inputSequence
    //         this.originalData.warehouseNo = this.warehouseNo
    //         this.originalData.discount = this.discount
    //         this.originalData.cooperateWay = this.cooperateWay
    //         this.originalData.remark = this.remark
    //       } else {
    //         // 判断是否修改了数据
    //         for (const key in this.originalData) {
    //           if (this.originalData.hasOwnProperty(key)) {
    //             const e = this.originalData[key]
    //             if (e != this[key]) {
    //               // 修改了数据 重新赋值
    //               isNew = true
    //               this.originalData.inputDate = this.inputDate
    //               this.originalData.customerNo = this.customerNo
    //               this.originalData.inputSequence = this.inputSequence
    //               this.originalData.warehouseNo = this.warehouseNo
    //               this.originalData.discount = this.discount
    //               this.originalData.cooperateWay = this.cooperateWay
    //               this.originalData.remark = this.remark
    //               break
    //             }
    //           }
    //         }
    //       }

    //       if (this.sequence != '' && !isNew) {
    //         // 有序号并且信息没改，再点读卡，传右表
    //         // console.log('没有数据变动')
    //       } else {
    //         // console.log('第一次或有数据变动')
    //         // 有数据变动，进厂序号改空
    //         this.sequence = ''
    //         this.switchList = []
    //         this.kindsNumberList = []
    //         this.styleNumberList = []
    //       }

    //       let d = {
    //         // 是否是补单（补货数据（0否 1是））
    //         isReplenishment: this.sequence ? 1 : 0,
    //         inputDate: this.inputDate,
    //         customerNo: this.customerNo,
    //         inputSequence: this.inputSequence,
    //         sequence: this.sequence,
    //         warehouseNo: this.warehouseNo,
    //         discount: this.discount,
    //         cooperateWay: this.cooperateWay,
    //         remark: this.remark,
    //         kindsNumberNumMap
    //       }
    //       // console.log(d)
    //       // return
    //       outByKindsNumberContinue(JSON.stringify(d)).then((res) => {
    //         this.$refs.upload.value = ''
    //         if (res.data.code == 200) {
    //           if (res.data.data.validList && res.data.data.validList.length) {
    //             this.sequence = res.data.data.validList[0].sequence
    //             this.getData(false)
    //           }
    //           if (res.data.data.outOfStock && res.data.data.outOfStock.length) {
    //             // 库存不足导出
    //             this.exportRaw(String(res.data.data.outOfStock), '库存不足.txt')
    //           }
    //           if (
    //             res.data.data.outOfStockPlus &&
    //             res.data.data.outOfStockPlus.length
    //           ) {
    //             // 部分成功导出
    //             this.exportRaw(
    //               String(res.data.data.outOfStockPlus),
    //               '部分成功.txt'
    //             )
    //           }
    //         }
    //       })
    //     } catch (error) {
    //       console.log(error)
    //       return false
    //     }
    //   }
    //   fileReader.readAsBinaryString(files[0])
    // },

    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const prop = column.property
        const values = data.map((item) => Number(item[prop]))
        if (!values.every((value) => isNaN(value))) {
          if (
            prop == 'c05' ||
            prop == 'c07' ||
            prop == 'c09' ||
            prop == 'c11' ||
            prop == 'c13' ||
            prop == 'c15' ||
            prop == 'c17' ||
            prop == 'c19' ||
            prop == 'c21' ||
            prop == 'c23' ||
            prop == 'f' ||
            prop == 'total' ||
            prop == 'sum' ||
            prop == 'sellingPriceMoney' ||
            prop == 'money'
          ) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            if (!sums[index]) {
              sums[index] = ''
            }
            let decimal = sums[index].toString().split('.')[1]
            if (decimal && decimal.length > 2) {
              sums[index] = sums[index].toFixed(2)
            }
          }
        }
      })
      return sums
    },

    newNo() {
      if (this.$route.query.oid || this.readOnly) return
      this.sequence = ''

      this.originalData = {}

      this.rfidList = []
      this.efficacious = []

      this.rfidListTable = []
      this.allRFIDlist = []

      this.switchList = []
      this.kindsNumberList = []
      this.styleNumberList = []
      this.inputSum = 0

      this.isConfirm = false
    },

    getData(fill) {
      this.twoDimensional = false
      let sequence = this.sequence
      getOutInquire({
        outSequence: sequence,
        limit: 99999,
        page: 1
      })
        .then((res) => {
          if (fill) {
            let f = res.data.data.outInquireTotalList[0]
            this.isConfirm = f.affirm
            this.customerNo = f.no
            this.inputDate = f.outTime + ' 00:00:00'
            this.warehouseNo = f.warehouseNo
            this.discount = res.data.data.outInquireInfoList[0].discount
            this.inputSequence = f.receiptsNumber || ''
            this.cooperateWay = f.cooperateWay || ''
            this.remark = f.remark || ''

            this.customerNoBlur()
            this.warehouseNoBlur()

            this.sequence = sequence
          }

          this.kindsNumberList = res.data.data.outInquireInfoList
          this.kindsNumberList.sort((a, b) => {
            return a.kindsNumber.localeCompare(b.kindsNumber)
          })
          this.switchList = this.kindsNumberList

          let s = 0
          this.kindsNumberList.forEach((e) => {
            e.colorNoName = e.colorNo + '.' + e.colorName
            s += e.sum
          })
          this.inputSum = s

          this.$nextTick(() => {
            this.$refs.table.doLayout()
          })

          return getOutInquire({
            twoInfo: 1,
            outSequence: sequence,
            limit: 999,
            page: 1
          })
        })
        .then((res) => {
          this.styleNumberList = res.data.data.customerOutInfoTwos
          this.styleNumberList.forEach((e) => {
            e.colorNoName = e.colorNo + '.' + e.colorName
            e.styleNumber = e.typeNumber
            e.total =
              Number(e.c05) +
              Number(e.c07) +
              Number(e.c09) +
              Number(e.c11) +
              Number(e.c13) +
              Number(e.c15) +
              Number(e.c17) +
              Number(e.c19) +
              Number(e.c21) +
              Number(e.c23) +
              Number(e.f)
            e.sellingPriceMoney = (e.total * e.sellingPrice).toFixed(2)

            if (e.c05 === 0) e.c05 = ''
            if (e.c07 === 0) e.c07 = ''
            if (e.c09 === 0) e.c09 = ''
            if (e.c11 === 0) e.c11 = ''
            if (e.c13 === 0) e.c13 = ''
            if (e.c15 === 0) e.c15 = ''
            if (e.c17 === 0) e.c17 = ''
            if (e.c19 === 0) e.c19 = ''
            if (e.c21 === 0) e.c21 = ''
            if (e.c23 === 0) e.c23 = ''
            if (e.f === 0) e.f = ''
          })
          return RfidList({
            sequence: sequence,
            type: 2
          })
        })
        .then((res) => {
          this.readOnly = false
          let len = res.data.data.length
          this.allRFIDlist = res.data.data || []
          this.rfidListTable = this.allRFIDlist
          this.allRFIDlist.sort((a, b) => {
            return a.showCode.localeCompare(b.showCode)
          })
          this.rfidList = []
          this.allRFIDlist.forEach((e) => {
            e.index = len--
            this.rfidList.push({ showCode: e.showCode })
          })
        })
    }
  },
  beforeDestroy() {
    if (this.ws.readyState == 1) this.ws.close()
  }
}
</script>
